using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell;

namespace DslCrossModelFramework.Environment {
    public class EnvironmentConfiguration {
        public static object syncRoot = new object();
        public static volatile IEnvironmentConfiguration environmentConfiguration;
        public static IEnvironmentConfiguration Current {
            get { 
                if(environmentConfiguration == null) {
                    foreach(IEnvironmentConfiguration config in configurations) {
                        if(config.IsActive) {
                            environmentConfiguration = config;
                        }
                    }
                    if(environmentConfiguration == null) {
                        throw new EnvironmentConfigurationNotFoundException();
                    }
                }

                return environmentConfiguration;
            }
        }

        /// <summary>
        /// Gets a value indicating whether an environment configuration is available.
        /// </summary>
        /// <value><c>true</c> if an environment configuration is available; otherwise, <c>false</c>.</value>
        public static bool EnvironmentAvailable {
            get {
                IDslIntegrationService service = Package.GetGlobalService(typeof(SDslIntegrationService)) as IDslIntegrationService;
                if(service != null) {
                    service.RegisterDefaultEnvironments();
                }
                foreach (IEnvironmentConfiguration config in configurations) {
                    if (config.IsActive) {
                        return true;
                    }
                }
                return false;
            }
        }

        private static List<IEnvironmentConfiguration> configurations = new List<IEnvironmentConfiguration>();

        public static void RegisterEnvironmentConfiguration(IEnvironmentConfiguration configuration) {
            foreach(IEnvironmentConfiguration config in configurations) {
                if(config.Name == configuration.Name) {
                    return;
                }
            }
            configurations.Add(configuration);
        }

        /// <summary>
        /// Clears the environment configuration registrations.
        /// </summary>
        public static void ClearRegistrations() {
            configurations.Clear();
        }
    }

    public class EnvironmentConfigurationNotFoundException : Exception {
        public EnvironmentConfigurationNotFoundException()
            : base(DslCrossModelFramework.Resources.Errors.MissingEnvironmentConfig) {}
    }
}